<?php
namespace App\Http\Controllers\Api;

use App\Helper\Utils\TimeUtil;
use App\V3\V3_1\Models\AdminModel;
use App\V3\V3_1\Models\SalesReturnGoodsDetailModel;
use App\V3\V3_1\Models\SalesReturnModel;
use App\V3\V3_1\Models\SalesReturnPayRecordModel;
use App\V3\V3_1\Models\SellDriverModel;
use App\V3\V3_1\Models\SellGoodsDetail;
use App\V3\V3_1\Models\SellModel;
use App\V3\V3_1\Models\SellOtherChargesModel;
use App\V3\V3_1\Models\SellPayRecord;
use App\V3\V3_1\Models\StorageManageModel;
use App\Services\IncomeExpensesService;
use App\Services\OutInRepealService;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Validator;

/**
 * 退货
 * Class SellController
 * @package App\Http\Controllers\Api
 */
class SalesReturnController extends BaseController
{
    /**
     * 退货列表
     * change 在 2021/11/3 15:20 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'pageSize' =>'required|integer',//页面大小
            'currentPage' =>'required|integer',//当前页
            'repeal_status'=>'required|integer'//撤销状态：0-未撤销 1-已撤销
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        //查询
        if($this->getUserId()==$this->getMainUserId()){
            $model = SalesReturnModel::where(['main_id'=>$this->getMainUserId(),'repeal_status'=>$data['repeal_status']])
                ->orderBy('id','desc')
                ->paginate($data['pageSize'],['*'], '',$data['currentPage'])
                ->toArray();
        }else{
            $model = SalesReturnModel::where(['main_id'=>$this->getMainUserId(),'repeal_status'=>$data['repeal_status'],'user_id'=>$this->getUserId()])
                ->orderBy('id','desc')
                ->paginate($data['pageSize'],['*'], '',$data['currentPage'])
                ->toArray();
        }
        if($model['data']){
            foreach ($model['data'] as &$value){
                $value['username'] = AdminModel::where('id',$value['user_id'])->value('username');
                $value['goods_info'] = SalesReturnGoodsDetailModel::where('return_id',$value['id'])->get();
            }
        }
        return $this->success($model);
    }

    /**
     * 详情
     * change 在 2021/11/3 10:09 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function find(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' =>'required|integer',//销售单主键id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $model = SalesReturnModel::find($data['id']);
        if($model){
            $model['username'] = AdminModel::where('id',$model['user_id'])->value('username');
            $model['goods_info'] = SalesReturnGoodsDetailModel::where('return_id',$model['id'])->get();
            foreach ($model['goods_info'] as &$val){
                $val['in_storage_num'] = StorageManageModel::where(['materiel_name'=>$val['name'],'type_name'=>$val['type_name'],'main_id'=>$this->getMainUserId()])->value('in_storage_num');
            }
        }
        return $this->success($model);
    }

    /**
     * 添加退货单
     * change 在 2021/11/3 15:21 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'customer_name' =>'required|string',//客户姓名
            'goods_info' =>'required|string',//商品信息  json array
            'discount' =>'integer',//折扣 ：百分比
            'tax_rate' =>'integer',//税率 ：百分比
            'is_zero_suppression' =>'required|integer',//是否改价：0-否 1-是
            'final_money' =>'string',//实际应收金额（即折扣或抹零后价格）如果是改价此参数必填
            'real_money' =>'string',//实付金额（实际入账）
            'remark' =>'string',//备注
            'out_order_no' =>'string',//外部单号
            'refund_date' =>'required|date',//退货时间
            'proof_image' =>'string',//凭证图片(多图逗号分隔)
            //            'is_draft' =>'required|integer',//是否草稿：1-是 0-否
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        //开启事务
        DB::beginTransaction();
        try{
            //报溢报损主单
            $mainInfo = $data;
            unset($mainInfo['goods_info']);
            $mainInfo['main_id'] = $this->getMainUserId();
            $mainInfo['user_id'] = $this->getUserId();
            $mainInfo['created_at'] = time();
            $mainInfo['refund_date'] = strtotime($data['refund_date']);
            $mainInfo['order_no'] = 'ST'. $this->getMainUserId().TimeUtil::getMillisecond();//订单号
            //创建销售主单信息
            $mainId = SalesReturnModel::insertGetId($mainInfo);
            //商品详细添加
            $goodsInfo = json_decode($data['goods_info'],true);
            $money = 0;//货款金额
            foreach ($goodsInfo as &$value){
                $value['main_id'] = $this->getMainUserId();
                $value['return_id'] = $mainId;
                $value['created_at'] = time();
                $money+=($value['price']*$value['num']);
            }

            //非改价计算价格
            if(!$data['is_zero_suppression'] && $money){
                $finalMoney = 0;
                if(isset($data['discount']) && $data['discount']){//折扣
                    $finalMoney+= ($data['discount']*$money/100);
                }else{
                    $finalMoney = $money;
                }

                if(isset($data['tax_rate']) && $data['tax_rate']){//加税点
                    $finalMoney+= ($data['tax_rate']*$finalMoney/100);
                }
                SalesReturnModel::where('id',$mainId)->update(['final_money'=>$finalMoney,'money'=>$money]);
            }else{
                SalesReturnModel::where('id',$mainId)->update(['money'=>$money]);
            }
            //实收全部结清更新支付状态为全部
//            if(isset($mainInfo['real_money']) && (string)$mainInfo['real_money']==(string)$finalMoney){
//                SalesReturnModel::where('id',$mainId)->update(['pay_status'=>2]);
//            }

            SalesReturnGoodsDetailModel::insert($goodsInfo);
            DB::commit();//提交事务
            return $this->success($mainId);
        }catch (Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(),'添加退货单');
        }
    }

    /**
     * 编辑销售单
     * change 在 2021/11/1 16:45 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function edit(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' =>'required|integer',//主键id
            'customer_name' =>'string',//客户姓名
            'goods_info' =>'string',//商品信息  json array [{"name":"测试","type_name":"规格","price":"2.30","num":2,"image":"商品图片地址","warehouse":"仓库名称","warehouse_id":1},{"name":"测试1","type_name":"规格","price":"2.30","num":22,"image":"商品图片地址","warehouse":"仓库名称1","warehouse_id":2}]
            'discount' =>'integer',//折扣 ：百分比
            'tax_rate' =>'integer',//税率 ：百分比
            'is_zero_suppression' =>'required|integer',//是否改价：0-否 1-是
            'final_money' =>'string',//实际应收金额（即折扣或抹零后价格）如果是改价此参数必填
            'real_money' =>'string',//实付金额（实际入账）
            'remark' =>'string',//备注
            'out_order_no' =>'string',//外部单号
            'refund_date' =>'date',//退货时间
            'proof_image' =>'string',//凭证图片(多图逗号分隔)
            //            'is_draft' =>'required|integer',//是否草稿：1-是 0-否
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        //开启事务
        DB::beginTransaction();
        try{
            //报溢报损主单
            $mainInfo = $data;
            if(isset($mainInfo['refund_date'])) $mainInfo['refund_date'] = strtotime($data['refund_date']);
            //商品详细添加
            if(isset($mainInfo['goods_info']) && !empty($mainInfo['goods_info'])){
                $goodsInfo = json_decode($data['goods_info'],true);
                $money = 0;//货款金额
                foreach ($goodsInfo as $value){
                    $money+=($value['price']*$value['num']);
                    $goods = SalesReturnGoodsDetailModel::where(['return_id'=>$data['id'],'name'=>$value['name'],'type_name'=>$value['type_name']])->first();
                    //更新
                    if($goods){
                        SalesReturnGoodsDetailModel::where(['return_id'=>$data['id'],'name'=>$value['name'],'type_name'=>$value['type_name']])->update($value);
                    }else{//添加
                        $value['main_id'] = $this->getMainUserId();
                        $value['return_id'] = $data['id'];
                        $value['created_at'] = time();
                        SalesReturnGoodsDetailModel::insert($value);
                    }

                }
                //非改价计算价格
                if(!$data['is_zero_suppression'] && $money){
                    $finalMoney = 0;
                    if(isset($data['discount']) && $data['discount']){//折扣
                        $finalMoney+= ($data['discount']*$money/100);
                    }else{
                        $finalMoney = $money;
                    }
                    if(isset($data['tax_rate']) && $data['tax_rate']){//加税点
                        if($finalMoney){
                            $finalMoney+= ($data['tax_rate']*$finalMoney/100);
                        }else{
                            $finalMoney+= ($data['tax_rate']*$money/100);
                        }
                    }
                    $mainInfo['final_money'] = $finalMoney;
                    $mainInfo['money'] = $money;
                }else{
                    $mainInfo['money'] = $money;
                }
                unset($mainInfo['goods_info']);
            }
            //更新销售单
            SalesReturnModel::where('id',$data['id'])->update($mainInfo);
            DB::commit();//提交事务
            return $this->success();
        }catch (Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(),'编辑退货单');
        }
    }

    /**
     * 删除退货单
     * change 在 2021/11/2 15:51 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function del(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id'=>'required|integer',//销售单主键
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        SalesReturnModel::where('id', $data['id'])->update(['delete_flag' => 1]);
        return $this->success();
    }
    /**
     * 付款
     * change 在 2021/11/1 16:47 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMoney(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'return_id'=>'required|integer',//退货单主键
//            'money'=>'numeric|min:0',//收款金额
            'collection_time'=>'required|date',//收款时间
            'collection_account'=>'required|string',//收款账号
            'status'=>'required|integer',//收款状态：1-全部 2-部分
        ], [
            'money.numeric' => '金额异常，只能为数字，请重新输入',
            'money.min' => '金额不能低于0'
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        //开启事务
        DB::beginTransaction();
        try{
            $model = SalesReturnModel::where('id',$data['return_id'])->first();//销售单信息
            $inMomey = SalesReturnPayRecordModel::where('return_id',$data['return_id'])->sum('money');//已收款金额
            //全部收款
            if($data['status']==1){
                $model->pay_status = 2;
                $model->real_money = $model->final_money;
                $model->save();
                $money = $model['final_money']-$inMomey;
            }else{//部分收款
                //收款超额检测
                if(($inMomey+$data['money'])>$model['final_money']){
                    return $this->fail('', '超出剩余应付金额');
                }
                if(($inMomey+$data['money'])<$model['final_money']){
                    $model->pay_status = 1;
                    $model->real_money = $inMomey+$data['money'];
                }
                if(($inMomey+$data['money'])==$model['final_money']){
                    $model->pay_status = 2;
                    $model->real_money = $model->final_money;
                }
                $model->save();
                $money = $data['money'];
            }
            //收款记录
            $data['collection_time'] = strtotime($data['collection_time']);
            $data['created_at'] = time();
            $data['main_id'] = $this->getMainUserId();
            unset($data['status']);
            $data['money'] = $money;
            SalesReturnPayRecordModel::insert($data);

            //账单记录
            IncomeExpensesService::tally(1,$model['order_no'],$money,$this->getMainUserId(), $model['refund_date']);
            DB::commit();//提交事务
            return $this->success();
        }catch (\Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail('','$e->getMessage()');
        }
    }

    /**
     * 撤销
     * change 在 2021/11/2 09:39 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function repeal(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id'=>'required|integer',//销售单主键
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $res = OutInRepealService::repeal($data['id'],2);

        if($res==0){
            return $this->fail('','商品被删除，无法撤销');
        }
        if($res==1){
            return $this->success();
        }
        if($res==2){
            return $this->fail('','库存数量不足，无法撤销');
        }

    }

    /**
     * 入库
     * change 在 2021/11/11 13:48 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function in(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' => 'required|integer',//退货单主键id
            'status' => 'required|integer',//出入库状态：0-部分 1-全部
            'goods_info' => 'string',//商品信息  array
            'in_storage_time'=>'required|date',//入库时间
            'remark' => 'string',//备注
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        if($data['status']==0){//部分
            $res = OutInRepealService::outIn(2,$data['id'],1,$data['goods_info'],$data);//入库处理
            if($res==1){
                return $this->fail('','数量不符无法入库');
            }
            if(is_array($res)){
                return $this->fail('',$res['msg']);
            }
        }else {//全部
            $res = OutInRepealService::outIn(2,$data['id'],2,'',$data);//入库处理
            if(is_array($res)){
                return $this->fail('',$res['msg']);
            }
        }
        DB::commit();//提交事务
        return $this->success();
    }
}
